﻿using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace LujWeb.Internal;

public class PageContentLoader {

  public async Task<PageContent> LoadAsync(string path) {
    string pageRaw = await File.ReadAllTextAsync(path);

    var findHead = () => {
      TagStart? head = FindTag("<head>", pageRaw, 0);
      if (head == null) {
        return (null, 0);
      }

      int start = head.AfterEnd;
      int end = pageRaw.IndexOf("</head>", start);
      return (pageRaw[start..end], end);
    };

    (string? headStr, int bodyFind) = findHead();
    TagStart? bodyTag = FindTag("<body>", pageRaw, bodyFind);
    Debug.Assert(bodyTag != null);

    int bodyStart = bodyTag.AfterEnd;
    int bodyEnd = pageRaw.IndexOf("</body>", bodyStart);
    string bodyStr = pageRaw[bodyStart..bodyEnd];

    return new(headStr, bodyStr, bodyTag.Attr);
  }

  record TagStart(int AfterEnd, string Attr);
  TagStart? FindTag(string name, string pageRaw, int findStart) {
    string namePre = name.TrimEnd('>');
    int nameStartIdx = pageRaw.IndexOf(namePre, findStart);
    if (nameStartIdx < 0) {
      return null;
    }

    int endIdx = pageRaw.IndexOf('>', nameStartIdx);
    Debug.Assert(endIdx >= 0);

    int attrStart = nameStartIdx + namePre.Length;
    string attr = pageRaw[attrStart..endIdx];

    int lineEnd = pageRaw.IndexOf('\n', nameStartIdx);
    if (lineEnd < 0) {
      return new(endIdx + 1, attr);
    }
    return new(lineEnd + 1, attr);
  }
}

public record PageContent(string? Head, string Body, string BodyAttr);
